package org.liang.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import org.liang.domain.TenantType;
import org.liang.mapper.TenantTypeMapper;
import org.liang.service.ITenantTypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liang
 * @since 2024-05-29
 */
@Service
public class TenantTypeServiceImpl extends ServiceImpl<TenantTypeMapper, TenantType> implements ITenantTypeService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    private static final String TENANT_TYPE_CACHE_KEY = "tenant_type_cache_key";

    @Override
    public List<TenantType> selectList(Wrapper<TenantType> wrapper) {
        //1.从缓存获取
        Object o = redisTemplate.opsForValue().get(TENANT_TYPE_CACHE_KEY);

        //2.有就直接返回
        if(Objects.nonNull(o)){
            return (List<TenantType>) o;
        }

        synchronized (TenantTypeServiceImpl.class){
            //1.从缓存获取
            o = redisTemplate.opsForValue().get(TENANT_TYPE_CACHE_KEY);

            //2.有就直接返回
            if(Objects.nonNull(o)){
                return (List<TenantType>) o;
            }
            //3.没有就去数据库查询
            List<TenantType> tenantTypes = super.selectList(wrapper);
            if(tenantTypes == null){
                tenantTypes = Arrays.asList(new TenantType());
            }

            //4.将查询结果放入缓存后返回数据库
            redisTemplate.opsForValue().set(TENANT_TYPE_CACHE_KEY,tenantTypes);
            return tenantTypes;
        }
    }
}
